package com.fz.crowdfunding.interceptor;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fz.crowdfunding.bean.User;
import com.fz.crowdfunding.util.Const;

public class LoginInterceptor extends HandlerInterceptorAdapter{
	//进入控制器之前执行
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		
		//定义哪些路径不需要拦截(白名单)
		Set<String> uri = new HashSet<String>();
		uri.add("/user/reg.do");//注册路径
		uri.add("/user/reg.htm");
		uri.add("/login.htm");//登录页面路径
		uri.add("/doLogin.do");
		uri.add("/logout.do");//注销功能路径
		
		//获取请求路径
		String servletPath = request.getServletPath();
		//判断请求路径是否在uri白名单中
		if(uri.contains(servletPath)){
			return true;
		}
		
		//判断用户是否登录，如登录则放行，未登录则跳转登录页面
		HttpSession session = request.getSession();
		
		User user = (User)session.getAttribute(Const.LOGIN_USER);
		
		if(user!=null){
			return true;
		}else{
			response.sendRedirect(request.getContextPath()+"/login.htm");
			return false;
		}
	}

}
